const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

// 测试配置
const BASE_URL = 'http://localhost:3000';
const TEST_UUID = 'your_test_uuid_here'; // 需要替换为有效的用户UUID

async function testAvatarUpload() {
  try {
    console.log('开始测试头像上传功能...');
    
    // 创建测试图片文件（如果不存在）
    const testImagePath = path.join(__dirname, 'test_avatar.png');
    if (!fs.existsSync(testImagePath)) {
      console.log('创建测试图片文件...');
      // 创建一个简单的PNG文件（1x1像素的透明图片）
      const pngBuffer = Buffer.from([
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D,
        0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
        0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00,
        0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00,
        0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49,
        0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82
      ]);
      fs.writeFileSync(testImagePath, pngBuffer);
    }
    
    // 创建FormData
    const form = new FormData();
    form.append('avatar', fs.createReadStream(testImagePath));
    
    // 发送请求
    const response = await axios.post(`${BASE_URL}/api/visitor/updateUserAvatar`, form, {
      headers: {
        ...form.getHeaders(),
        'uuid': TEST_UUID
      },
      timeout: 30000 // 30秒超时
    });
    
    console.log('✅ 头像上传成功！');
    console.log('响应数据:', response.data);
    
  } catch (error) {
    console.error('❌ 头像上传测试失败:');
    if (error.response) {
      console.error('状态码:', error.response.status);
      console.error('错误信息:', error.response.data);
    } else {
      console.error('网络错误:', error.message);
    }
  }
}

// 运行测试
if (require.main === module) {
  testAvatarUpload();
}

module.exports = { testAvatarUpload }; 